<?php
declare (strict_types = 1);
/**
 * Created by PhpStorm.
 * User: broceli
 * Date: 19-9-9
 * Time: 下午2:20
 */
namespace app\middleware;

use app\Lib\Jwt\Jwt;
use think\Request;
use Closure;

class JwtMiddleware{

    const NO_CHECK_AUTH = [
        '/login',
        '/',
        '/index/index',
    ];
    public function handle(Request $request, Closure $next) {
        $url = $request->url();
        $response = $next($request);
        if(!in_array($url, self::NO_CHECK_AUTH)){
            if(!$this->checkAuth()){
                $data=['code'=>-1, 'msg'=>'请先登录'];
                $response->data(json_encode($data));
            }
        }
        return $response;
    }

    private function checkAuth()
    {
        $header = request()->header();
        try {
            $token = Jwt::parseToken($header['token']);
        } catch (\Exception $e) {
            throw new \Exception('token 解析失败', 50000); //格式错误
        }

        try {
            if(Jwt::validateToken($token, $header['uid']) === false){
                throw new \Exception('token失效,请重新登录', 50001);
            }
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        return true;
    }
}
